package com.jbinfo.qingcaowan.studyManager.service;

import javax.annotation.Resource;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.jbinfo.common.utils.DataTables;
import com.jbinfo.common.utils.UUIDUtils;
import com.jbinfo.qingcaowan.base.dao.BaseTimeDao;
import com.jbinfo.qingcaowan.base.dto.BaseTimeDTO;
import com.jbinfo.qingcaowan.common.ClonePojoUtil;
import com.jbinfo.qingcaowan.common.JSONResult;
import com.jbinfo.qingcaowan.studyManager.dao.BookManagerDao;
import com.jbinfo.qingcaowan.studyManager.dao.CardManagerDao;
import com.jbinfo.qingcaowan.studyManager.dao.CycleDetailDao;
import com.jbinfo.qingcaowan.studyManager.dto.BookCardModel;
import com.jbinfo.qingcaowan.studyManager.dto.BookCycleDTO;
import com.jbinfo.qingcaowan.studyManager.dto.BookInfoDTO;
import com.jbinfo.qingcaowan.studyManager.dto.CardTaskDTO;
import com.jbinfo.qingcaowan.studyManager.dto.CycleDetailCardDTO;
import com.jbinfo.qingcaowan.studyManager.dto.CycleDetailDTO;
import com.jbinfo.qingcaowan.studyManager.entity.BookCard;
import com.jbinfo.qingcaowan.studyManager.entity.BookInfo;
import com.jbinfo.qingcaowan.studyManager.entity.CycleDetail;
import com.jbinfo.qingcaowan.studyManager.entity.CycleDetailCard;
import com.jbinfo.qingcaowan.studyManager.entity.CycleMain;
import com.jbinfo.qingcaowan.studyManager.service.CardManagerService;

/**
 * 
* @ClassName: CardManagerServiceImpl 
* @Description: TODO 卡片管理service实现类
* @author ZhangLei 
* @date 2016年6月22日 上午10:23:02
 */
@Service("cardManagerService")
public class CardManagerServiceImpl implements CardManagerService {
	
	private static Logger log = LoggerFactory.getLogger(CardManagerServiceImpl.class);
	
	@Resource(name="cardManagerDao")
	private CardManagerDao cardManagerDao;
	
	@Resource(name="bookManagerDao")
	private BookManagerDao bookManagerDao;
	
	@Resource(name="cycleMainService")
	private CycleMainService cycleMainService;
	
	@Resource(name="cycleDetailDao")
	private CycleDetailDao cycleDetailDao;
	
	@Resource(name="baseTimeDao")
	private BaseTimeDao baseTimeDao;

	@Override
	public BookCard getCardInfo(String cardId) {
		BookCard bookCard = new BookCard();
		bookCard.setCardId(cardId);
		return cardManagerDao.getBookCardInfo(bookCard);
	}

	@Override
	public int editBookCard(BookCard bookCard) {
		return cardManagerDao.editBookCard(bookCard);
	}

	@Override
	public int delBookCard(String cardId) {
		return cardManagerDao.delBookCard(cardId);
	}

	@Override
	public DataTables<BookCard> getCardList(BookCardModel bookCardModel) {
		String today = bookCardModel.getCreateTime();
		bookCardModel.setCreateTime1(today+" 00:00:00");
		bookCardModel.setCreateTime2(today+" 23:59:59");
		List<BookCard> tList = cardManagerDao.getCardList(bookCardModel);
		for(int i=0;i<tList.size();i++){
			tList.get(i).setNo((i+1)+"");
		}
		return DataTables.combinTotalRecords(tList);
	}
	
	@Override
	public void save(BookCard bookCard) {
		//处理卡片主键
		String cardId = UUIDUtils.create();
		bookCard.setCardId(cardId);	
		cardManagerDao.save(bookCard);
	}

	@Override
	public List<BookCard> getCardByCode(BookCard bookCard) {
		return cardManagerDao.getCardByCode(bookCard);
	}

	@Override
	public List<BookCard> queryCardList(BookCard bookCard) {
		return cardManagerDao.queryCardList(bookCard);
	}

	// 查询学习计划及卡片内容    总阅读时间 及 百分比（当前天数/总阅读天数）
	@Override
	public Object findBookCycle(CycleMain cycleMain) {
		// 获取当前阅读天数、阅读时间、阅读百分比
		
		CycleMain cycleMainDetail = new CycleMain();
		cycleMainDetail.setOrgId(cycleMain.getOrgId());
		cycleMainDetail.setQueryDate(cycleMain.getQueryDate());
		JSONResult cycleJson = (JSONResult) cycleMainService.findCycleDetail(cycleMainDetail); 
		List<CycleDetailDTO> cycleList = cycleJson.getResultBean();
		
		// 当前阅读天数
		Integer nCurTaskDate = Integer.valueOf(0);
		// 阅读时间
		Integer taskTime = Integer.valueOf(0);
		// 总阅读天数
		//Integer nCycleDate = Integer.valueOf(0);
		Integer nTotalTaskDate = Integer.valueOf(0);
		// 阅读百分比
//		String strReadRate = "";
						
		if (cycleList != null && !cycleList.isEmpty()) {
			CycleDetailDTO cycleDetailDTO = cycleList.get(0);
			// 当前阅读天数
			nCurTaskDate = cycleDetailDTO.getTaskOrder();
			// 阅读时间
			taskTime = cycleDetailDTO.getTaskTime();
			// 总阅读天数
			//nCycleDate = cycleDetailDTO.getCycleDate();
			nTotalTaskDate = cycleDetailDTO.getnTotalTaskDate();
			// 阅读百分比
			//strReadRate = cycleDetailDTO.getReadRate();
		}
		
		String bookId = cycleMain.getBookId();
		
		// 获取书籍简介等内容
		BookInfo bookInfo = bookManagerDao.selectByPrimaryKey(bookId);
		
		// 将BookInfo 拷贝到 BookInfoDTO 对象中
		BookInfoDTO bookInfoDTO = 
				ClonePojoUtil.copyClassFromTo(bookInfo, BookInfoDTO.class);
		
		bookInfoDTO.setnCurTaskDate(nCurTaskDate);
		bookInfoDTO.setTaskTime(taskTime);
		bookInfoDTO.setnCycleDate(nTotalTaskDate);
		//bookInfoDTO.setStrReadRate(strReadRate);
		
		// 获取书籍目录
		List<CycleDetail> cycleDetaiList = cardManagerDao.findChapterAndCardName(bookId);
		
		CycleDetailCard cycleDetailCard = new CycleDetailCard();
		/*String strTaskDate = cycleMain.getQueryDate();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date dTaskDate = null;
		try {
			dTaskDate = sdf.parse(strTaskDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			log.error("日期格式不正确");
			throw new BusinessException(BusinessExceptionCode.parse_format_error, "日期格式错误");
		}*/
		cycleDetailCard.setTaskDate(cycleMain.getQueryDate());
		cycleDetailCard.setUserId(cycleMain.getUserId());
		List<BookCard> bookCardList = cardManagerDao.findCardInfoByCyCle(cycleDetailCard);
		
		CycleDetailCardDTO cycleDetailCardDTO = new CycleDetailCardDTO();
		
		// 总卡片数
		Integer nCardCnt = cardManagerDao.findCardCntByTaskDate(cycleDetailCard);
		
		// 阅读百分比
		String cardReadRate = "0";
//		List<BookCard> cardList = new ArrayList<BookCard>();
		
		// 最小卡片顺序，最大卡片顺序
		Integer minCardNumber = Integer.valueOf(0);
		Integer maxCardNumber = Integer.valueOf(0);
		if (bookCardList != null && !bookCardList.isEmpty()) {
			BookCard minBookCard = bookCardList.get(0);
			minCardNumber = minBookCard.getCardNumber();
			
			int nMaxIndex = bookCardList.size()-1;
			BookCard maxBookCard = bookCardList.get(nMaxIndex);
			maxCardNumber = maxBookCard.getCardNumber();
			
			// 根据第几张卡片与卡片总数比值计算阅读百分比
//			for (int i = 0; i < bookCardList.size(); i++) {
//				int nLastCardNum = i;
//				NumberFormat numberFormat = NumberFormat.getInstance();
//				numberFormat.setMaximumFractionDigits(2);
//				cardReadRate = numberFormat.format((float)nLastCardNum/(float)nCardCnt);
//				
//				BookCard bookCard = bookCardList.get(i);
//				BookCard card = ClonePojoUtil.copyClassFromTo(bookCard, BookCard.class);
//				card.setCardReadRate(cardReadRate);
//				cardList.add(card);
//			}
		}
		cardReadRate = getCardReadRate(cycleDetailCard).toString();
		log.info("cardReadRate: " + cardReadRate);
		
		cycleDetailCardDTO.setMinCardNumber(minCardNumber);
		cycleDetailCardDTO.setMaxCardNumber(maxCardNumber);
		cycleDetailCardDTO.setCardCnt(nCardCnt);
		cycleDetailCardDTO.setCardReadRate(cardReadRate);
		
		return new BookCycleDTO(bookInfoDTO, cycleDetaiList, bookCardList, cycleDetailCardDTO);
	}
	
	// 根据 cardNumber、 taskDate 获取卡片内容
	public Object getCardInfoByNumber(CycleDetailCardDTO cardDTO) {
		
		CycleDetailCard cycleDetailCard = new CycleDetailCard();
		
		Integer cardNumber = Integer.valueOf(cardDTO.getCardNumber());
		cycleDetailCard.setCardNumber(cardNumber);
		cycleDetailCard.setTaskDate(cardDTO.getTaskDate());
		
		List<BookCard> bookCardList = cardManagerDao.findCardInfoByCyCle(cycleDetailCard);
		
		// 获取cardId
		BookCard bookCard = bookCardList.get(0);
		String cardId = bookCard.getCardId();
		String userId = cardDTO.getUserId();
		// 根据userId、cardId 获取该卡片阅读时间
		BaseTimeDTO baseTimeDTO = new BaseTimeDTO();
		baseTimeDTO.setUserId(userId);
		baseTimeDTO.setCardId(cardId);
		// 学习任务日期
//		Date dTaskDay = cardDTO.getTaskDate();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		String strQueryDate = sdf.format(dTaskDay);
//		baseTimeDTO.setStrQueryDate(strQueryDate);
		// 根据userId、cardId、学习任务日期查询该用户查询日期是否阅读过该卡片
		Integer nTime = baseTimeDao.findCardIsReaded(baseTimeDTO);
		
		String isReaded = "0"; // 0为未阅读，1为已阅读
		if (nTime != null && nTime.intValue() > 0) {
			isReaded = "1";
		}
		
		CycleDetailCard cycleCard = new CycleDetailCard();
		cycleCard.setTaskDate(cardDTO.getTaskDate());
		List<BookCard> cardList = cardManagerDao.findCardInfoByCyCle(cycleCard);
		CycleDetailCardDTO cycleDetailCardDTO = new CycleDetailCardDTO();
		
		Integer nCardCnt = cardManagerDao.findCardCntByTaskDate(cycleDetailCard);
		
		// 最小卡片顺序，最大卡片顺序
		Integer minCardNumber = Integer.valueOf(0);
		Integer maxCardNumber = Integer.valueOf(0);
		
		// 阅读百分比
		String cardReadRate = "0";
		
		if (cardList != null && !cardList.isEmpty()) {
			BookCard minBookCard = cardList.get(0);
			minCardNumber = minBookCard.getCardNumber();
			
			int nMaxIndex = cardList.size()-1;
			BookCard maxBookCard = cardList.get(nMaxIndex);
			maxCardNumber = maxBookCard.getCardNumber();
//			// 从第二张卡片开始计算阅读百分比
//			if (cardList.size() > 1) {
//				for (int i = 0; i < cardList.size(); i++) {
//					if (i>=1) {
//						BookCard card = cardList.get(i);
//						// 根据cardNumber 判断现在阅读第几张卡片
//						if (cardNumber.intValue() == card.getCardNumber().intValue()) {
//							int nLastCardNum = i;
//							NumberFormat numberFormat = NumberFormat.getInstance();
//							numberFormat.setMaximumFractionDigits(2);
//							cardReadRate = numberFormat.format((float)nLastCardNum/(float)nCardCnt);
//						}
//						
//					}
//				}
//			}
			
		}
		// 阅读百分比
		cycleDetailCard.setUserId(userId);  // 用户ID
		cardReadRate = getCardReadRate(cycleDetailCard).toString();
		
		cycleDetailCardDTO.setMinCardNumber(minCardNumber);
		cycleDetailCardDTO.setMaxCardNumber(maxCardNumber);
		cycleDetailCardDTO.setCardCnt(nCardCnt);
		// 是否已阅读
		cycleDetailCardDTO.setIsReaded(isReaded);
		
		// 阅读百分比
		cycleDetailCardDTO.setCardReadRate(cardReadRate);
		
		return new CardTaskDTO(bookCardList, cycleDetailCardDTO);
	}

	@Override
	public Object getCardReadRate(CycleDetailCard cycleDetailCard) {
		String cardReadRate = "0";
		// 根据查询日期查询保存阅读时间的卡片数
		Date dQueryDate = cycleDetailCard.getTaskDate();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String strQueryDate = sdf.format(dQueryDate);
		BaseTimeDTO baseTimeDTO = new BaseTimeDTO();
		baseTimeDTO.setUserId(cycleDetailCard.getUserId());
		baseTimeDTO.setStrQueryDate(strQueryDate);
		
		List<BaseTimeDTO> readCardList = baseTimeDao.findCardReadedNum(baseTimeDTO);
		
		Integer nReadCardNum = Integer.valueOf(readCardList.size());
		// 查询当天学习计划中的总卡片数
		Integer nCardCnt = cardManagerDao.findCardCntByTaskDate(cycleDetailCard);
		
		NumberFormat numberFormat = NumberFormat.getInstance();
		numberFormat.setMaximumFractionDigits(2);
		cardReadRate = numberFormat.format((float)nReadCardNum/(float)nCardCnt);
		
		return cardReadRate;
	}

}
